/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2017-2020. All rights reserved.
 * Description: ai remote file writer
 */
#include "ai_stats_file_writer.h"

#include "infra/base/assertion.h"
#include "infra/memory_manager/client/fd_manager_ddk.h"
#include "infra/rpc/rpc_request_client.h"
#include "infra/rpc/serialize.h"

using namespace hiai::rpc;

namespace hiai {
int FileWriter::Write(const AiStatsEngineType type, std::string message)
{
    OutStream os;
    os << type << message;
    std::string codestr = os.str();
    int fd =
        hiai::FdManager::CreateFdAndFlush(hiai::ION_ALLOC_NAME, static_cast<size_t>(codestr.size()), codestr.data());
    HIAI_EXPECT_TRUE_R(fd >= 0, -1);
    std::vector<hiai::rpc::RpcHandle> input = {{fd, static_cast<int>(codestr.size())}};
    std::vector<hiai::rpc::RpcHandle> output;
    Status res =
        rpc::RpcRequestClient::GetInstance().Execute(0, AI_STATS_MODULEID, CMD_AI_STATS_WRITE_FILE, input, output);
    if (res != SUCCESS) {
        STATS_LOGE("Write message error");
        hiai::FdManager::DestroyFd(fd);
        return -1;
    }
    hiai::FdManager::DestroyFd(fd);
    return 0;
}
};  // namespace hiai
